package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDto;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.pojo.vo.WeiboDetailVO;
import cn.tedu.weibo.pojo.vo.WeiboIndexVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo/")
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;
    @RequestMapping("insert")
    public int insert(@RequestBody WeiboDto weibo, HttpSession session){
        //得到登录成功时保存的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        //如果没有值代表未登录, 告诉客户端去做登录操作
        if (user==null){
            return 2;
        }
        Weibo w = new Weibo();
        BeanUtils.copyProperties(weibo,w);//把dto的数据保存到实体里面
        w.setCreated(new Date()); //设置发布时间
        w.setUserId(user.getId());// 设置发布作者id
        mapper.insert(w);
        return 1;
    }
    @RequestMapping("select")
    public List<WeiboIndexVO> select(){
        return mapper.select();
    }
    @RequestMapping("selectById")
    public WeiboDetailVO selectById(int id){

        return mapper.selectById(id);
    }
}
